/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

/**
 *
 * @author Hallucinogen
 */
public class Message {
    public Message() {
        mLength = 0;
    }

    public Message(int length, byte type, String content){
        mLength     = length;
        mType       = type;
        mContent    = content;
    }

    public void setLength(int len) {
        mLength = len;
    }

    public void setType(byte type) {
        mType = type;
    }

    public void setContent(String content) {
        mContent = content;
    }

    public int getLength() {
        return mLength;
    }

    public byte getType() {
        return mType;
    }

    public String getContent() {
        return mContent;
    }

    @Override
    public String toString() {
        if (mLength == 0)
            return "0000";

        String lenStr = "";
        lenStr += (char)((mLength >> 24) % 256);
        lenStr += (char)((mLength >> 16) % 256);
        lenStr += (char)((mLength >> 8) % 256);
        lenStr += (char)(mLength % 256);

        return lenStr + (char)mType + mContent;
    }

    public byte[] toByte() {
        String str = toString();
        byte[] retval = new byte[str.length()];

        for (int i = 0; i < str.length(); ++i)
            retval[i] = (byte)str.charAt(i);

        return retval;
    }

    public static Message fromString(String str) {
        Message retval = new Message();

        int res = 0;
        for (int i = 0; i < 4; ++i) {
            res = (res * 256) + (int)str.charAt(i);
            //System.out.println((int)str.charAt(i));
        }

        retval.mLength  = res;
        retval.mType    = (byte)str.charAt(4);
        StringBuilder sb = new StringBuilder();

        for (int i = 5; i < str.length(); ++i) {
            sb.append(str.charAt(i));
        }

        retval.mContent = sb.toString();

        return retval;        
    }

    private int mLength;
    private byte mType;
    private String mContent;

    public static final byte MESSAGE_BITFIELD   = 5;
    public static final byte MESSAGE_REQUEST    = 6;
    public static final byte MESSAGE_PIECE      = 7;
}
